package com.gjy.dubbo.service.provider.service.nacos;

import com.gjy.dubbo.service.domain.vo.GetConfigsRequest;
import com.gjy.dubbo.service.domain.vo.NacosAuthLoginRequest;
import com.gjy.dubbo.service.domain.vo.NacosAuthLoginResponse;
import com.gjy.dubbo.service.nacos.NacosConfigService;
import com.gjy.dubbo.service.nacos.NacosConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-06-12 13:41:47
 */
@DubboService()
@Service
@Slf4j
public class NacosConfigServiceImpl implements NacosConfigService {

    @Resource
    private RestTemplate restTemplate;

    private static final String PREFIX = "http://192.168.200.148:8848";

    @Override
    public NacosAuthLoginResponse authLogin(NacosAuthLoginRequest request) {
        String password = request.getPassword();
        String username = request.getUsername();

        String url = String.format(PREFIX + NacosConstant.NACOS_V1_AUTH_LOGIN + "?username=%s&password=%s",
                username, password);
        log.info("username={}, password={}\nurl={}", username, password, url);
        NacosAuthLoginResponse post = restTemplate.postForObject(url, null, NacosAuthLoginResponse.class);
        log.info("response = {}", post);
        return post;
    }

    @Override
    public String getConfigs(GetConfigsRequest request) {
        String accessToken = request.getAccessToken();
        String group = request.getGroup();
        String dataId = request.getDataId();
        String tenant = request.getTenant();

        String url = String.format(PREFIX + NacosConstant.NACOS_V1_CS_CONFIGS_GET + "?accessToken=%s&dataId=%s&group=%s&tenant=%s",
                accessToken, dataId, group, tenant);
        log.info("accessToken={},grou={},dataId={},tenant={}\nurl={}",
                accessToken, group, dataId, tenant, url);

        String s = restTemplate.getForObject(url, String.class);
        log.info("s = {}", s);
        return s;
    }

}
